<template>
  <el-form
    ref="formRef"
    :inline="true"
    v-loading="formLoading"
    :model="formData"
    :rules="formCopyright"
    label-width="130px"
  >
    <span><h3>数字资源版权信息</h3></span>
    <el-form-item label="资源名称:" prop="name">
      <el-input
        v-model="formData.name"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入资源名称"
      />
    </el-form-item>

    <el-form-item label="资源类型:" prop="type">
      <el-input
        v-model="formData.type"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入资源类型"
      />
    </el-form-item>
    <br />
    <el-form-item label="版权编号:" prop="copyrightNumber">
      <el-input
        v-model="formData.copyrightNumber"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入版权编号"
      />
    </el-form-item>
    <el-form-item label="著作权人:" prop="copyrightAuthor">
      <el-input
        v-model="formData.copyrightAuthor"
        class="!w-240px"
        clearable
        :disabled="disabled"
        placeholder="请输入著作权人"
      />
    </el-form-item>
    <br />
    <el-form-item label="版权期限:" prop="validity">
      <el-radio-group v-model="formData.validity" class="!w-240px">
        <el-radio label="0" size="large">{{ validitys.always }}</el-radio>
        <el-radio label="1" size="large">{{ validitys.notAlways }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="选择时间:" prop="time" v-if="formData.validity == '1'">
      <el-date-picker
        v-model="formData.datetime"
        type="daterange"
        start-placeholder="请选择开始日期"
        end-placeholder="请选择结束日期"
        class="!w-260px"
        @change="handelChangeTime"
      />
    </el-form-item>
    <el-divider />
    <span><h4>资源信息(必填)</h4></span>
    <el-form-item>
      <el-button plain type="primary" @click="onAddItem()">
        <Icon class="mr-5px" icon="ep:plus" />
        添加资源
      </el-button>
    </el-form-item>
    <br />
    <el-tabs type="border-card" @tab-click="selectTab" :model-value="activeName">
      <el-tab-pane label="图书库" name="42">
        <ContentWrap>
          <el-table v-loading="ResourceLoading" :data="mateList.list">
            <el-table-column type="selection" width="55" />
            <el-table-column
              v-for="(column, index) in mateList.columns"
              :key="index"
              :prop="column.prop"
              :label="column.label"
              align="center"
            >
              <template #default="scope">
                <el-image
                  v-if="imaged(scope.row[column.prop])"
                  :src="buildImage(column.prop, scope.row)"
                  style="max-width: 50px"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="资源状态">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.RESOURCE_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
          </el-table>
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="图片库" name="picture">
        <ContentWrap>
          <el-table
            v-loading="ResourceLoading"
            :data="pictureList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" prop="url" label="图片">
              <template #default="{ row }">
                <el-image :src="row.url" style="max-width: 100px" @click="imagePreview(row.url)" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="名称" />
            <el-table-column align="center" prop="size" label="尺寸" />
            <el-table-column align="center" prop="format" label="格式" />
            <el-table-column align="center" prop="fileSize" label="大小" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="视频库" name="video">
        <ContentWrap>
          <el-table
            v-loading="ResourceLoading"
            :data="videoList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="left" prop="name" label="名称" width="150" />
            <el-table-column align="center" prop="ext" label="格式" />
            <el-table-column align="left" prop="fileSize" label="大小" width="100" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
        </ContentWrap>
      </el-tab-pane>
      <!-- <el-tab-pane label="音频库" name="audio" :disabled="audioDisabled"> -->
      <el-tab-pane label="音频库" name="audio">
        <ContentWrap>
          <el-table
            v-loading="ResourceLoading"
            :data="audioList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="left" prop="url" label="音频" width="320">
              <template #default="{ row }">
                <audio :src="row.url" controls></audio>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="name" label="名称" />
            <el-table-column align="center" prop="ext" label="格式" />
            <el-table-column align="left" prop="fileSize" label="大小" width="100" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
          <!-- <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="videoList.total"
            @pagination="handelQuery('audio')"
          /> -->
        </ContentWrap>
      </el-tab-pane>
    </el-tabs>
  </el-form>
  <div style="text-align: center; margin-top: 40px" class="affix-container">
    <el-affix position="bottom" target=".affix-container">
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button type="primary" @click="submitFormClose">保存并关闭</el-button>
      <el-button type="primary" @click="resetForm">重置</el-button>
      <el-button type="primary" @click="router.go(-1)">关闭</el-button>
    </el-affix>
  </div>
  <SelectResource ref="selectResourceRef" @ResourcesListChange="ResourcesListChange" />
</template>
<script lang="ts" setup>
import * as CopyrightApi from '@/api/copyright/copyright'
import * as microCopyrightApi from '@/api/copyright/microCopyright'
import router from '@/router'
import { useRoute } from 'vue-router'
import SelectResource from '@/views/common/SelectResource.vue'
import { DICT_TYPE } from '@/utils/dict'
import * as metaApi from '@/api/meta'

defineOptions({ name: 'microCopyrightForm' })

const end = new Date() // 时间选择器
const start = new Date()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const disabled = ref(false) // 禁用输入框
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const validitys = ref({ always: '永久版权', notAlways: '非永久版权' }) // 版权期限
const formDataCopyrightStatus = ref({ normal: '正常', notValidity: '已过期' }) // 版权状态

const selectResourceRef = ref()
const ResourceLoading = ref(false) // 列表的加载中
const activeName = ref('42')
const tempData = ref([]) //临时数据
const mateList = ref([]) // 资源列表图书库
const pictureList = ref([])
const videoList = ref([])
const audioList = ref([])
const resourceList = ref([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: null,
  createTime: []
})
/** 重置资源列表 */
const restTabs = () => {
  if (mateList.value.length == 0) {
    initMateList(activeName.value)
  }
  resourceList.value = []
  pictureList.value = []
  videoList.value = []
  audioList.value = []
  mateList.value.list = []
}
/** 初始化资源图书列表 */
const initMateList = async (name) => {
  mateList.value = await metaApi.selectData(name, queryParams)
  tempData.value = mateList.value.list
  mateList.value.list = []
}
/** 添加资源选中数据 */
const ResourcesListChange = async (list: any, name: string): Promise<void> => {
  ResourceLoading.value = true
  activeName.value = name
  if (name == 'picture') {
    pictureList.value.list = list
  } else if (name == 'video') {
    videoList.value.list = list
  } else if (name == 'audio') {
    audioList.value.list = list
  } else {
    mateList.value.list = list
  }
  ResourceLoading.value = false
}

const formData = ref({
  id: 0,
  copyrightAuthor: '',
  name: '',
  doi: '',
  type: '',
  copyrightNumber: '',
  copyrightValidity: '',
  copyrightStatus: '',
  validity: '0',
  repository: '',
  datetime: [end, start]
})

/** 重置表单 */
const resetForm = () => {
  restTabs()
  formData.value = {
    id: 0,
    copyrightAuthor: '',
    name: '',
    doi: '',
    type: '',
    copyrightNumber: '',
    copyrightValidity: '',
    copyrightStatus: '',
    validity: '0',
    repository: '',
    datetime: [start, end]
  }
  formRef.value?.resetFields()
}
/** 资源表格修改时重置 */
const restTabsUpdate = () => {
  resourceList.value = []
  pictureList.value = []
  videoList.value = []
  audioList.value = []
}
/** 资源列表 */
const getListCopyrightResources = async () => {
  //重置资源列表
  restTabsUpdate()
  const id = formData.value.id
  const data = await microCopyrightApi.getMicroCopyrightResources(id)
  const PictureFiltered = data.filter((item) => item.type === 43)
  const VideoFiltered = data.filter((item) => item.type === 48)
  const AudioFiltered = data.filter((item) => item.type === 51)
  const MateFiltered = data.filter((item) => item.type === 42)
  if (Array.isArray(PictureFiltered) && PictureFiltered.length > 0) {
    const resourceIds = PictureFiltered.map((item) => item.resourceId)
    const list = await CopyrightApi.getPictureList(resourceIds)
    ResourcesListChange(list, 'picture')
  }
  if (Array.isArray(VideoFiltered) && VideoFiltered.length > 0) {
    const resourceIds = VideoFiltered.map((item) => item.resourceId)
    const list = await CopyrightApi.getVideoList(resourceIds)
    ResourcesListChange(list, 'video')
  }
  if (Array.isArray(AudioFiltered) && AudioFiltered.length > 0) {
    const resourceIds = AudioFiltered.map((item) => item.resourceId)
    const list = await CopyrightApi.getAudioList(resourceIds)
    ResourcesListChange(list, 'audio')
  }
  if (Array.isArray(MateFiltered) && MateFiltered.length > 0) {
    const resourceIds = MateFiltered.map((item) => item.resourceId)
    tempData.value
      .filter((item) => resourceIds.includes(item.id))
      .forEach((element) => {
        mateList.value.list.push(element)
      })
  }
}

const formCopyright = reactive({
  name: [{ required: true, message: '资源名称不能为空', trigger: 'change' }],
  type: [{ required: true, message: '资源类型不能为空', trigger: 'change' }],
  copyrightNumber: [{ required: true, message: '版权编号不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 添加资源 */
const onAddItem = async () => {
  selectResourceRef.value.openDialog()
}

/** 资源时间修改事件 */
const handelChangeTime = (val: any) => {
  formData.value.datetime = val
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
/** 保存并关闭 */
const submitFormClose = async () => {
  submitForm()
  router.go(-1)
}
const submitForm = async () => {
  // 版权状态默认正常 后期检查是否过期
  formData.value.copyrightStatus = formDataCopyrightStatus.value.normal
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    addItemTime(formData.value.validity)
    addResource()
    const microCopyrightData = formData.value as unknown as microCopyrightApi.microCopyrightVO
    const resourceData = resourceList.value as unknown as microCopyrightApi.CopyrightMicroResources
    if (type === '新增') {
      let data = {
        microCopyrightData: microCopyrightData,
        resourceData: resourceData
      }
      await microCopyrightApi.createCopyright(data)
      message.success(t('common.createSuccess'))
    } else {
      let data = {
        microCopyrightData: microCopyrightData,
        resourceData: resourceData
      }
      await microCopyrightApi.updateCopyright(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 新增资源 */
const addResource = async () => {
  let nestedArray = []
  let picture = []
  let video = []
  let audio = []
  let mate = []
  if (pictureList.value.list != undefined) {
    picture = pictureList.value.list.map((item: any) => ({
      ...item,
      type: 43,
      metaId: 43,
      resourceId: item.id
    }))
  }
  if (videoList.value.list != undefined) {
    video = updateResource(48, videoList.value.list)
  }
  if (audioList.value.list != undefined) {
    audio = updateResource(51, audioList.value.list)
  }
  if (mateList.value.list != undefined) {
    mate = mateList.value.list.map((item) => {
      const { fn_cover, ...rest } = item // 使用对象解构来排除 id 字段
      return {
        type: 42,
        metaId: 42,
        resourceId: item.id,
        ...rest // 将剩余的字段添加回新的对象中
      }
    })
  }
  nestedArray.push(picture)
  nestedArray.push(video)
  nestedArray.push(audio)
  nestedArray.push(mate)
  let ss = [].concat(...nestedArray)
  resourceList.value = ss
}
const updateResource = (type, list) => {
  return list.map((item: any) => ({
    ...item,
    type: type,
    metaId: type,
    resourceId: item.id
  }))
}
/** 更新有效期 */
const addItemTime = async (status: any) => {
  if (status == '0') {
    formData.value.copyrightValidity = validitys.value.always
  } else {
    var startString = formData.value.datetime[0]
      .toLocaleDateString('zh-CN', { year: 'numeric', month: 'numeric', day: 'numeric' })
      .replace(/\//g, '/')
    var endString = formData.value.datetime[1]
      .toLocaleDateString('zh-CN', { year: 'numeric', month: 'numeric', day: 'numeric' })
      .replace(/\//g, '/')
    formData.value.copyrightValidity = startString + ' - ' + endString
  }
}
const route = useRoute()
const type = route.query.type
const id = route.query.id
const info = async () => {
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await microCopyrightApi.getCopyright(id)
      if (formData.value.validity == '0') {
        formData.value.copyrightValidity = validitys.value.always
      } else {
        formData.value.datetime = [
          new Date(formData.value.copyrightValidity.split('-')[0]),
          new Date(formData.value.copyrightValidity.split('-')[1])
        ]
      }
      getListCopyrightResources()
    } finally {
      formLoading.value = false
    }
  }
}
/** 商品图预览 */
const imagePreview = (args) => {
  const urlList = []
  if (isArray(args)) {
    args.forEach((item) => {
      urlList.push(item.url)
    })
  } else {
    urlList.push(args)
  }
  createImageViewer({
    urlList
  })
}

function isNumber(str: string): boolean {
  return /^\d+$/.test(str) // 只包含数字的正则表达式
}

const imaged = (row) => {
  if (!row) {
    return false
  }
  if (isNumber(row)) {
    return false
  }
  return isValidJson(row)
}
const buildImage = (name, row) => {
  if (JSON.parse(row[name]).length > 0) {
    return JSON.parse(row[name].replaceAll('\\', ''))[0].url
  } else {
    return ''
  }
}

function isValidJson(str) {
  if (str.startsWith('{') || str.startsWith('[')) {
    if (str.endsWith(']') || str.endsWith('}')) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}
onMounted(() => {
  info()
  restTabs()
})
</script>
<style lang="scss" scoped>
.eidt-row-p {
  width: 100%;
  height: 32px;
  margin: 0;
  line-height: 32px;
  text-align: center;
}

// 设置表格中输入框为边框为0
.ipt {
  width: 60px;
  height: 23px;
  margin-right: 5px;
  border: 1px solid rgb(187 187 187 / 100%);
  border-radius: 3px;
  outline: none;
}

.div-A {
  width: 45%;
  height: 200px;
}

.div-B {
  width: 50%;
  height: 200px;
}

.div-C {
  width: 50%;
  height: 200px;
}

.inline-div {
  display: inline-block;
}
</style>
